#!/bin/bash

SERVICE_SHORT_NAME=""
TAR_NAME_PATTERN=""
TARGET_STATUS=200
TARGET_FILE=""

function help() {
  echo "Usage:"
  echo "smp.sh [-n mcc-smp-web-service] [-s command]"
  echo "example: mcc.sh -n mcc-smp-web-service -s 4"
  echo "Description:";
  echo "command: -n <SERVICE_NAME>"
  echo "command: -s 0 unInstall"
  echo "command: -s 1 install"
  echo "command: -s 2 stop"
  echo "command: -s 3 start"
  echo "command: -s 4 unInstall,install,start"
  exit;
}

while getopts ":n:s:h:" opt
do
    case $opt in
        n)
        echo "service-short-name: $OPTARG"
 SERVICE_SHORT_NAME=$OPTARG;
        ;;
        s)
        echo "OPT--$OPTARG"
 TARGET_STATUS=$OPTARG;;
h) help;;
\?) help ;


  read -r -p "Are You Sure? [Y/n] " input
    case $input in
    [yY][eE][sS]|[yY])
      echo "$input"
      ;;
    [nN][oO]|[nN])
      exit 1
    ;;
    *)
    echo "Invalid input..."
    exit 1
    ;;
    esac
        ;;
        ?)
        echo "---$opt"
        exit 1;;
    esac
done

function stop(){
  /usr/mcc/server/"$SERVICE_SHORT_NAME"/bin/shutdown.sh
}

function run(){
/usr/mcc/server/"$SERVICE_SHORT_NAME"/bin/startup.sh
}

function install(){
  tar -zxvf "$TARGET_FILE" -C /usr/mcc/server/
}

function unInstall(){
  rm -rf /usr/mcc/server/"$SERVICE_SHORT_NAME"
  rm -rf /usr/mcc/logs/"$SERVICE_SHORT_NAME"*
}
## 判断 -n
 if [ "$SERVICE_SHORT_NAME" == '' ]
  then
   echo "Please input service short name.example: [-n mcc-smp-web-service]"
   exit 1
 else
   TAR_NAME_PATTERN="*$SERVICE_SHORT_NAME.*"
      TARGET_FILE=$(find /usr/mcc/update/ -name "$TAR_NAME_PATTERN" |xargs ls -alt| head -n 1 | awk '{print $9}' );
      echo "target file: $TARGET_FILE"
 fi

 ## 判断 target file
if [ ! -f "$TARGET_FILE" ]
  then
    echo "file not find"
    exit 1
fi

## 判断是安装还是卸载 0卸载  1 安装  2:停止 3:启动
if [ "$TARGET_STATUS" == '0' ];
then
   stop
   unInstall
elif [ "$TARGET_STATUS" == '1' ];
  then
    install
elif [ "$TARGET_STATUS" == '2' ];
  then
    stop
elif [ "$TARGET_STATUS" == '3' ];
  then
    run
elif [ "$TARGET_STATUS" == '4' ];
  then
    stop
    unInstall
    install
    run
else
  echo "Please input:[-s 0/1/2/3/4] 0:uninstall/1:install/2:stop/3:run/4:unInstall install run"
fi